package com.example.a13001.shoppingmalltemplate.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.a13001.shoppingmalltemplate.MainActivity;
import com.example.a13001.shoppingmalltemplate.R;
import com.example.a13001.shoppingmalltemplate.application.ShoppingMallTemplateApplication;
import com.example.a13001.shoppingmalltemplate.base.AppConstants;
import com.example.a13001.shoppingmalltemplate.base.BaseActivity;
import com.example.a13001.shoppingmalltemplate.manager.DataManager;
import com.example.a13001.shoppingmalltemplate.modle.User;
import com.example.a13001.shoppingmalltemplate.utils.MyUtils;
import com.example.a13001.shoppingmalltemplate.utils.SPUtils;
import com.example.a13001.shoppingmalltemplate.utils.Utils;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;


public class LoginActivity extends BaseActivity {

    @BindView(R.id.login_register_tv)
    TextView loginRegisterTv;
    @BindView(R.id.login_forget_tv)
    TextView loginForgetTv;
    private static final String TAG = "LoginActivity";
    @BindView(R.id.login_phone_et)
    EditText loginPhoneEt;
    @BindView(R.id.login_pw_et)
    EditText loginPwEt;
    @BindView(R.id.iv_login_back)
    ImageView ivLoginBack;
    private DataManager manager;
    private CompositeSubscription mCompositeSubscription;
    private User mUser;
    private String mType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        manager = new DataManager(LoginActivity.this);
        mCompositeSubscription = new CompositeSubscription();

        if (getIntent() != null) {
            mType = getIntent().getStringExtra("type");
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @OnClick({R.id.login_register_tv, R.id.login_forget_tv, R.id.btn_login_commit, R.id.login_wx, R.id.login_qq, R.id.login_sina})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //注册
            case R.id.login_register_tv:
                startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
                break;
            //忘记密码
            case R.id.login_forget_tv:
                startActivity(new Intent(LoginActivity.this, ForgetPwdActivity.class));
                break;
            //登录
            case R.id.btn_login_commit:
                String userName = loginPhoneEt.getText().toString().trim();
                String pwd = loginPwEt.getText().toString().trim();
                if (TextUtils.isEmpty(userName)) {
                    Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(pwd)) {
                    Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                String safetyCode = MyUtils.getMetaValue(LoginActivity.this, "safetyCode");
                String code = Utils.md5(safetyCode + Utils.getTimeStamp());

                doLogin(AppConstants.COMPANY_ID, code, Utils.getTimeStamp(), userName, pwd, "mobile");
//
//                finish();
                break;
            //qq登录
            case R.id.login_qq:
                Platform qq = ShareSDK.getPlatform(QQ.NAME);
                thirdLogin(qq);
                break;
            //微信登录
            case R.id.login_wx:
                Platform wechat = ShareSDK.getPlatform(Wechat.NAME);
                thirdLogin(wechat);
                break;
            //微博登录
            case R.id.login_sina:
                Platform sina = ShareSDK.getPlatform(SinaWeibo.NAME);
                thirdLogin(sina);
                break;
        }
    }

    private void thirdLogin(Platform platform) {
        if (platform.isAuthValid()) {
            platform.removeAccount(true);
            return;
        }
        platform.setPlatformActionListener(new PlatformActionListener() {

            private String sex;

            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                if (i == Platform.ACTION_USER_INFOR) {
                    PlatformDb platDB = platform.getDb();//获取数平台数据DB
                    //通过DB获取各种数据
                    platDB.getToken();
                    platDB.getUserGender();
                    String icon = platDB.getUserIcon();
                    String profit = platDB.getUserId();
                    String nickname = platDB.getUserName();
                    String openid = platDB.getUserId();
                    String gender = platDB.getUserGender();
                    Iterator ite = hashMap.entrySet().iterator();
                    if ("m".equals(gender)) {
                        sex = "1";
                    } else {
                        sex = "2";
                    }

                    Log.e(TAG, "onComplete: " + icon + "profit=" + profit + "nickname=" + nickname + "openid=" + openid + "gender=" + gender + "sex=" + sex);
                    String safetyCode = MyUtils.getMetaValue(LoginActivity.this, "safetyCode");
                    String code = Utils.md5(safetyCode + Utils.getTimeStamp());
                    MyUtils.putSpuString("openid", openid);
                    MyUtils.putSpuString("nickname", nickname);
                    MyUtils.putSpuString("sex", sex);
                    MyUtils.putSpuString("headimgurl", icon);
                    doThirdLogin(AppConstants.COMPANY_ID, code, Utils.getTimeStamp(), AppConstants.LOGINTYPE_WECHAT, openid, nickname, sex, icon,AppConstants.androidos,MyUtils.getImei(),  platform);
//                    isThirdLogin(icon, profit, nickname);
                }
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                Log.e("aaa",
                        "(LoginActivity.java:159)" + "onError");
            }

            @Override
            public void onCancel(Platform platform, int i) {
                Log.e("aaa",
                        "(LoginActivity.java:165)" + "onCancel");
            }
        });
        platform.showUser(null);
    }

    /**
     * 登录
     *
     * @param companyid 站点ID
     * @param code      安全校验码
     * @param timestamp 时间戳
     * @param name      会员名称，用户名/手机/邮箱
     * @param pwd       登录密码
     * @param from      来源，pc 电脑端 mobile 移动端
     */
    public void doLogin(String companyid, String code, String timestamp, final String name, final String pwd, String from) {
        mCompositeSubscription.add(manager.doLogin(companyid, code, timestamp, name, pwd, from)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<User>() {
                               @Override
                               public void onCompleted() {
                                   int status = mUser.getStatus();
                                   if (status > 0) {
                                       //设置标签（同上）
                                       JPushInterface.setTags(LoginActivity.this, 0, setUserTags());
                                       ShoppingMallTemplateApplication.loginType = "phone";
                                       MyUtils.putSpuString(AppConstants.USER_NAME, name);
                                       MyUtils.putSpuString(AppConstants.USER_PWD, pwd);
                                       MyUtils.putSpuString("logintype", "phone");
                                       switch (mType) {
                                           case "Setting":
                                               Intent intent = new Intent();
                                               intent.putExtra("login", "登录成功");
//                                               setResult(11,intent);
//                                               finish();
                                               startActivity(new Intent(LoginActivity.this, MainActivity.class).putExtra("type", "Login"));
                                               finish();
                                               break;
                                           case "allorder":
                                               Intent intent1 = new Intent();
                                               intent1.putExtra("login", "登录成功");
                                               setResult(11, intent1);
                                               finish();
                                               break;
                                           case "login":
                                               Intent intent2 = new Intent();
                                               intent2.putExtra("login", "登录成功");
                                               setResult(11, intent2);
                                               finish();
                                               break;
                                           default:

//                                       startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                               break;
                                       }

                                   } else {
                                       Toast.makeText(LoginActivity.this, "" + mUser.getReturnMsg(), Toast.LENGTH_SHORT).show();
                                   }
                               }

                               @Override
                               public void onError(Throwable e) {
                                   Log.e(TAG, "onError: " + e.toString());
                                   Toast.makeText(LoginActivity.this, "数据请求失败", Toast.LENGTH_SHORT).show();
                               }

                               @Override
                               public void onNext(User user) {
                                   Log.e(TAG, "onNext: " + user.toString());
                                   mUser = user;

                               }
                           }

                ));
    }

    /**
     * 标签用户
     */
    private static Set<String> setUserTags() {
        //添加3个标签用户（获取登录userid较为常见）
        Set<String> tags = new HashSet<>();
        tags.add("member");
        return tags;
    }

    /**
     * 第三方登录
     *
     * @param companyid  站点ID
     * @param code       安全校验码
     * @param timestamp  时间戳
     * @param type       qqlogin QQ登录， wxlogin 微信登录，sinalogin 新浪微博登录
     * @param openid     第三方登录用户唯一值
     * @param nickname   会员昵称
     * @param sex        会员性别，1 男，2 女
     * @param headimgurl 头像地址
     * @param platform
     * @return
     */
    public void doThirdLogin(String companyid, String code, String timestamp, String type, final String openid, final String nickname, final String sex, final String headimgurl,String appos,String appkey, final Platform platform) {
        mCompositeSubscription.add(manager.doThirdLogin(companyid, code, timestamp, type, openid, nickname, sex, headimgurl,appos,appkey)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<User>() {
                               @Override
                               public void onCompleted() {
                                   int status = mUser.getStatus();
                                   if (status > 0) {
                                       JPushInterface.setTags(LoginActivity.this, 0, setUserTags());
                                       String name = platform.getName();
                                       if ("QQ".equals(name)) {
                                           ShoppingMallTemplateApplication.loginType = "qq";
                                           MyUtils.putSpuString("logintype", "qq");
                                       } else {
                                           MyUtils.putSpuString("logintype", "wechat");
                                           ShoppingMallTemplateApplication.loginType = "wechat";
                                       }
                                       SPUtils.remove(LoginActivity.this, AppConstants.USER_NAME);
                                       SPUtils.remove(LoginActivity.this, AppConstants.USER_PWD);
                                       startActivity(new Intent(LoginActivity.this, MainActivity.class).putExtra("type", "Login"));
                                       finish();
                                   } else {
                                       Toast.makeText(LoginActivity.this, "" + mUser.getReturnMsg(), Toast.LENGTH_SHORT).show();
                                   }
                               }

                               @Override
                               public void onError(Throwable e) {
                                   Log.e(TAG, "onError: " + e.toString());
                                   Toast.makeText(LoginActivity.this, "数据请求失败", Toast.LENGTH_SHORT).show();
                               }

                               @Override
                               public void onNext(User user) {
                                   Log.e(TAG, "onNext: " + user.toString());
                                   mUser = user;

                               }
                           }

                ));
    }

    @Override
    public void onBackPressed() {
        Intent intent2 = new Intent();
        intent2.putExtra("login", "登录失败");
        setResult(11, intent2);
        super.onBackPressed();
    }

    @OnClick(R.id.iv_login_back)
    public void onViewClicked() {
        onBackPressed();
    }
}
